package com.ryder.book_cycle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ryder.book_cycle.entity.*;
import com.ryder.book_cycle.mapper.BookMapper;
import com.ryder.book_cycle.mapper.BookOrderMapper;
import com.ryder.book_cycle.mapper.MerchantProfileMapper;
import com.ryder.book_cycle.mapper.UserAccountMapper;
import com.ryder.book_cycle.service.UserAccountService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 描述: 用户账号表(UserAccount)表服务实现类
 * 
 * @author Ryder
 * @version 1.0
 * @since 1.0 // 版本号，指明从哪个版本开始
 * 更新日期: 2025-07-08 16:40:48
 */
@Service("userAccountService")
@RequiredArgsConstructor
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    private final MerchantProfileMapper merchantProfileMapper;

    private final BookMapper bookMapper;

    private final BookOrderMapper bookOrderMapper;

    @Override
    public boolean existsMerchantId(Long id) {
        return merchantProfileMapper.exists(new LambdaQueryWrapper<MerchantProfile>()
                .eq(MerchantProfile::getMerchantId, id));
    }

    @Override
    public boolean add(UserAccount entity) {
        boolean saved = this.save(entity);
        if (saved && entity.getUserType() == 1) {
            MerchantProfile merchantProfile = new MerchantProfile();
            merchantProfile.setMerchantId(entity.getId());
            merchantProfile.setShopName(entity.getUsername());
            merchantProfile.setContact(entity.getUsername());
            merchantProfile.setPhone(entity.getPhone());
            int insert = merchantProfileMapper.insert(merchantProfile);
            return insert > 0;
        }
        return saved;
    }

    @Override
    public HomeInfoDTO queryHomeInfoById(Long id) {
        // 获取在售书籍数量
        Long bookCount = bookMapper.selectCount(new LambdaQueryWrapper<Book>()
                .eq(Book::getMerchantId, id)
                .eq(Book::getStatus, 1));
        // 获取订单数量
        Long orderCount = bookOrderMapper.selectCount(new LambdaQueryWrapper<BookOrder>()
                .eq(BookOrder::getMerchantId, id));
        // 本月销售额
        Double totalPrice = bookOrderMapper.sumCurrentMonthSales(id, 2);
        HomeInfoDTO homeInfoDTO = new HomeInfoDTO();
        homeInfoDTO.setBookCount(bookCount);
        homeInfoDTO.setOrderCount(orderCount);
        homeInfoDTO.setTotalPrice(totalPrice);
        return homeInfoDTO;
    }
}
